package com.pml.dao.impl;

import com.pml.dao.IEmpDAO;
import com.pml.vo.Emp;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class EmpDAOImpl implements IEmpDAO{
    private Connection conn;
    private PreparedStatement pstmt;

    public EmpDAOImpl(Connection conn){
        this.conn=conn;
    }

    @Override
    public boolean doCreate(Emp emp) throws Exception {
        boolean flag=false;
        String sql="INSERT INTO emp(empno,ename,job,hiredate,sal) values (?,?,?,?,?)";
        pstmt=conn.prepareStatement(sql);
        pstmt.setInt(1,emp.getEmpno());
        pstmt.setString(2,emp.getEname());
        pstmt.setString(3,emp.getJob());
        pstmt.setDate(4,(Date) (emp.getHiredate()));
        pstmt.setFloat(5,emp.getSal());
        if (pstmt.executeUpdate()>0){
            flag=true;
        }
        System.out.println(flag);
        pstmt.close();
        return flag;
    }

    @Override
    public List<Emp> findAll(String keyword) throws Exception {
        List<Emp> empList= new ArrayList<Emp>();
        String sql="SELECT empno,ename,job,hiredate,sal FROM emp where ename LIKE ? OR job LIKE ?";
        pstmt=conn.prepareStatement(sql);
        pstmt.setString(1,"%"+keyword+"%");
        pstmt.setString(2,"%"+keyword+"%");
        ResultSet resultSet=pstmt.executeQuery();
        Emp emp=null;
        while (resultSet.next()){
            emp=new Emp();
            emp.setEmpno(resultSet.getInt(1));
            emp.setEname(resultSet.getString(2));
            emp.setJob(resultSet.getString(3));
            emp.setHiredate(resultSet.getDate(4));
            emp.setSal(resultSet.getFloat(5));
            empList.add(emp);
        }
        pstmt.close();
        return empList;
    }

    @Override
    public Emp findById(int empno) throws Exception {
        String sql="SELECT empno,ename,job,hiredate,sal FROM emp where empno=?";
        pstmt=conn.prepareStatement(sql);
        pstmt.setInt(1,empno);
        ResultSet resultSet=pstmt.executeQuery();
        Emp emp=null;
        if (resultSet.next()){
            emp=new Emp();
            emp.setEmpno(resultSet.getInt(1));
            emp.setEname(resultSet.getString(2));
            emp.setJob(resultSet.getString(3));
            emp.setHiredate(resultSet.getDate(4));
            emp.setSal(resultSet.getFloat(5));
        }
        pstmt.close();
        return emp;
    }
}
